package com.yqy.spring.reviewAnnotation;

import java.io.File;
import java.net.URL;
import java.nio.file.Files;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * 当Bean类上有Component注解时，则实例化Bean对象，如果没有，则不实例化对象
 */
public class Test {
    public static void main(String[] args) {
        Map<String,Object> beanMap=new HashMap<>();
        String path="com/yqy/spring/reviewAnnotation/bean";
        //这里有个大坑，必须为非中文路径，否则遍历文件会空指针异常
        URL url = ClassLoader.getSystemClassLoader().getResource(path);
        File file=new File(url.getPath());
        File[] files = file.listFiles();
        Arrays.stream(files).forEach(f->{
            try {
                String className = path.replaceAll("/",".")+"."+f.getName().split("\\.")[0];
                Class<?> clazz = Class.forName(className);
                if(clazz.isAnnotationPresent(Component.class)){
                    Component annotation = clazz.getAnnotation(Component.class);
                    String beanId=annotation.value();
                    Object bean = clazz.newInstance();
                    beanMap.put(beanId,bean);
                }
            } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
                throw new RuntimeException(e);
            }
        });
        System.out.println(beanMap);
    }
}
